package mundo.java.client;

import java.util.Map;

import mundo.java.client.events.Event;
import mundo.java.client.events.FailureEvent;
import mundo.java.client.events.GreetingResponseEvent;
import mundo.java.client.events.ListMessagesEvent;
import mundo.java.client.events.StartupEvent;
import mundo.java.client.events.Event.Handler;
import mundo.java.shared.GreetingAction;
import mundo.java.shared.GreetingResponse;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class MessagesPresenter {
	@Inject
	public MessagesPresenter(final GreetingServiceAsync service, final HandlerManager eventBus) {
		final AsyncCallback<Map<GreetingAction, GreetingResponse>> cb = 
		new AsyncCallback<Map<GreetingAction, GreetingResponse>>() {
			@Override
			public void onFailure(Throwable caught) {
				eventBus.fireEvent(new FailureEvent(caught));
			}

			@Override
			public void onSuccess(Map<GreetingAction, GreetingResponse> result) {
				// Apenas uma implementação "tosca" para mostrar que o presenter está pronto,
				// bem antes que tenhamos preparado nenhum código da view!!!
				// DESACOMPLAMENTO TOTAL, PRESENTER E SERVIÇOS READY FOR PRODUCTION!
				eventBus.fireEvent(new ListMessagesEvent(result));
			}
		};
		
		eventBus.addHandler(StartupEvent.TYPE, new Handler<StartupEvent>() {
			@Override
			public void onEvent(StartupEvent e) {
				service.list(cb);
			}
		});
		
		eventBus.addHandler(GreetingResponseEvent.TYPE, new Handler() {
			@Override
			public void onEvent(Event e) {
				service.list(cb);
			}
		});
	}
}